import 'package:flutter/material.dart';
import '../models/word_book.dart';
import '../models/learning_progress.dart';
import '../models/word_card.dart';
import '../models/word_library.dart';
import '../data/word_book_service.dart';
import '../widgets/book_info_widget.dart';
import '../widgets/learning_progress_widget.dart';
import '../widgets/app_bottom_navigation.dart';
import '../widgets/word_card_widget.dart';
import 'book_list_page.dart';
import 'placeholder_page.dart';
import 'speed_reading_page.dart';
import 'follow_reading_page.dart';
import 'challenge_page.dart';
import 'test_page.dart';
import 'dart:async';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:audioplayers/audioplayers.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _currentTabIndex = 0;
  WordBook? _currentBook;
  LearningProgress? _learningProgress;
  bool _isLoading = true;
  
  @override
  void initState() {
    super.initState();
    _loadCurrentBook();
  }
  
  Future<void> _loadCurrentBook() async {
    setState(() {
      _isLoading = true;
    });
    
    try {
      // 尝试获取当前选中的词书
      WordBook? book = await WordBookService.getCurrentBook();
      
      // 如果没有选中的词书，则使用第一本示例词书
      if (book == null) {
        final books = await WordBookService.getSampleBooks();
        if (books.isNotEmpty) {
          book = books.first;
          await WordBookService.setCurrentBook(book);
        }
      } else {
        // 确保已有词书使用最新的实际单词数量
        final actualTotalWords = await WordBookService.getBookTotalWords(book.id);
        if (book.totalWords != actualTotalWords) {
          book = WordBook(
            id: book.id,
            name: book.name,
            coverImage: book.coverImage,
            totalWords: actualTotalWords,
            description: book.description,
            category: book.category,
            data: book.data,
          );
          await WordBookService.setCurrentBook(book);
        }
      }
      
      if (book != null) {
        // 先同步数据，确保获取最新的学习进度
        await WordBookService.syncProgressAndLibrary(book.id);
        
        final progress = await WordBookService.getBookProgress(
          book.id, 
          book.totalWords
        );
        
        setState(() {
          _currentBook = book;
          _learningProgress = progress;
          _isLoading = false;
        });
      } else {
        setState(() {
          _isLoading = false;
        });
      }
    } catch (e) {
      print('加载词书失败: $e');
      setState(() {
        _isLoading = false;
      });
    }
  }
  
  void _onBookSelected(WordBook book) async {
    Navigator.pop(context); // 关闭词书列表页面
    
    setState(() {
      _isLoading = true;
    });
    
    try {
      await WordBookService.setCurrentBook(book);
      final progress = await WordBookService.getBookProgress(
        book.id, 
        book.totalWords
      );
      
      setState(() {
        _currentBook = book;
        _learningProgress = progress;
        _isLoading = false;
      });
    } catch (e) {
      print('设置词书失败: $e');
      setState(() {
        _isLoading = false;
      });
    }
  }
  
  void _showBookList() {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => BookListPage(
          onBookSelected: _onBookSelected,
        ),
      ),
    );
  }
  
  void _showHistoryRecords() {
    if (_learningProgress == null) return;
    
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => HistoryRecordsDrawer(
        progress: _learningProgress!,
      ),
    );
  }
  
  void _navigateToSpeedReadingMode() async {
    if (_currentBook == null) return;
    
    try {
      final words = await WordBookService.getSpeedReadingWords(_currentBook!.id);
      
      if (words.isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('没有更多单词可学习')),
        );
        return;
      }
      
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => SpeedReadingPage(
            wordBook: _currentBook!,
            words: words,
          ),
        ),
      ).then((_) => _loadCurrentBook()); // 返回首页时重新加载数据
    } catch (e) {
      print('加载单词失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('加载单词失败: $e')),
      );
    }
  }
  
  void _navigateToFollowReadingMode() async {
    if (_currentBook == null) return;
    
    try {
      final words = await WordBookService.getFollowReadingWords(_currentBook!.id);
      
      if (words.isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('新词词库为空，请先使用速读模式添加单词')),
        );
        return;
      }
      
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => FollowReadingPage(
            wordBook: _currentBook!,
            words: words,
          ),
        ),
      ).then((_) => _loadCurrentBook()); // 返回首页时重新加载数据
    } catch (e) {
      print('加载单词失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('加载单词失败: $e')),
      );
    }
  }
  
  void _navigateToChallengeMode() async {
    if (_currentBook == null) return;
    
    try {
      final words = await WordBookService.getChallengeWords(_currentBook!.id);
      
      if (words.isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('复习词库为空，请先使用速读模式和跟读模式学习单词')),
        );
        return;
      }
      
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => ChallengePage(
            wordBook: _currentBook!,
            words: words,
          ),
        ),
      ).then((_) => _loadCurrentBook()); // 返回首页时重新加载数据
    } catch (e) {
      print('加载单词失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('加载单词失败: $e')),
      );
    }
  }
  
  void _navigateToPlaceholderPage(String title, IconData icon, String message) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => PlaceholderPage(
          title: title,
          icon: icon,
          message: message,
        ),
      ),
    );
  }
  
  void _onTabChanged(int index) {
    setState(() {
      _currentTabIndex = index;
    });
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _buildCurrentTab(),
      bottomNavigationBar: AppBottomNavigation(
        currentIndex: _currentTabIndex,
        onTap: _onTabChanged,
      ),
    );
  }
  
  Widget _buildCurrentTab() {
    switch (_currentTabIndex) {
      case 0:
        return _buildHomeTab();
      case 1:
        return _buildPlaceholderTab('词书', Icons.menu_book, '词书功能正在开发中，敬请期待！');
      case 2:
        return _buildPlaceholderTab('我的', Icons.person, '个人中心功能正在开发中，敬请期待！');
      default:
        return _buildHomeTab();
    }
  }
  
  Widget _buildHomeTab() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }
    
    if (_currentBook == null || _learningProgress == null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text('未找到词书'),
            ElevatedButton(
              onPressed: _showBookList,
              child: const Text('选择词书'),
            ),
          ],
        ),
      );
    }
    
    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 第一行：应用标题
          Container(
            width: double.infinity,
            padding: const EdgeInsets.fromLTRB(16.0, 50.0, 16.0, 16.0),
            decoration: BoxDecoration(
              color: Colors.blue
            ),
            child: Text(
              '旺卡单词',
              style: TextStyle(
                fontSize: 28,
                fontWeight: FontWeight.bold,
                color: Colors.white,
              ),
            ),
          ),
          
          SizedBox(height: 20),
          
          // 第二行：词书信息
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            child: BookInfoWidget(
              book: _currentBook!,
              onMoreBooks: _showBookList,
            ),
          ),
          
          SizedBox(height: 20),
          
          // 第三行：学习进度
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            child: LearningProgressWidget(
              progress: _learningProgress!,
              onViewHistory: _showHistoryRecords,
            ),
          ),
          
          SizedBox(height: 20),
          
          // 第四行：学习模式
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  '学习模式',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 16),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    _buildModeButton(
                      Icons.speed,
                      '速读模式',
                      '快速浏览单词',
                      _navigateToSpeedReadingMode,
                    ),
                    _buildModeButton(
                      Icons.record_voice_over,
                      '跟读模式',
                      '听读跟读单词',
                      _navigateToFollowReadingMode,
                    ),
                    _buildModeButton(
                      Icons.fitness_center,
                      '挑战模式',
                      '测试掌握程度',
                      _navigateToChallengeMode,
                    ),
                  ],
                ),
              ],
            ),
          ),
          
          SizedBox(height: 20),
          
          // 第五行：测试页面入口
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: ElevatedButton(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => const TestPage()),
                );
              },
              style: ElevatedButton.styleFrom(
                minimumSize: const Size.fromHeight(50),
              ),
              child: const Text('打开单词加载测试页面'),
            ),
          ),
          
          SizedBox(height: 20), // 底部额外空间
        ],
      ),
    );
  }
  
  Widget _buildModeButton(
    IconData icon,
    String title,
    String description,
    VoidCallback onTap,
  ) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(12.0),
      child: Container(
        width: MediaQuery.of(context).size.width * 0.25,
        padding: const EdgeInsets.all(12.0),
        decoration: BoxDecoration(
          color: Colors.blue.withOpacity(0.1),
          borderRadius: BorderRadius.circular(12.0),
          border: Border.all(color: Colors.blue.withOpacity(0.3)),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(icon, color: Colors.blue, size: 32),
            const SizedBox(height: 8.0),
            Text(
              title,
              style: const TextStyle(
                fontSize: 14.0,
                fontWeight: FontWeight.bold,
                color: Colors.blue,
              ),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 4.0),
            Text(
              description,
              style: TextStyle(
                fontSize: 10.0,
                color: Colors.grey[600],
              ),
              textAlign: TextAlign.center,
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
          ],
        ),
      ),
    );
  }
  
  Widget _buildPlaceholderTab(String title, IconData icon, String message) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            icon,
            size: 80,
            color: Colors.grey[400],
          ),
          const SizedBox(height: 16),
          Text(
            message,
            style: TextStyle(
              fontSize: 18,
              color: Colors.grey[600],
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }
}

class WordCarouselPage extends StatefulWidget {
  final List<WordCard> sampleWords;

  WordCarouselPage({required this.sampleWords});

  @override
  _WordCarouselPageState createState() => _WordCarouselPageState();
}

class _WordCarouselPageState extends State<WordCarouselPage> {
  final CarouselSliderController _carouselController = CarouselSliderController();
  final WordCarouselLogic _logic = WordCarouselLogic();

  @override
  void initState() {
    super.initState();
    print('Initializing WordCarouselPage');
    _logic.init(this, widget.sampleWords, _carouselController);
  }

  @override
  void dispose() {
    _logic.dispose();
    print('Disposing WordCarouselPage');
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('速读模式'),
      ),
      body: Column(
        children: [
          Expanded(
            child: Container(
              height: MediaQuery.of(context).size.height * 0.5,
              child: CarouselSlider.builder(
                itemCount: widget.sampleWords.length,
                itemBuilder:
                    (BuildContext context, int itemIndex, int pageViewIndex) {
                  return WordCardWidget(
                    wordCard: widget.sampleWords[itemIndex],
                    showDetails:
                        _logic.showDetails && _logic.currentIndex == itemIndex,
                    onTap: () {
                      setState(() {
                        if (_logic.currentIndex == itemIndex) {
                          _logic.toggleShowDetails();
                        } else {
                          _logic.setCurrentIndex(itemIndex);
                        }
                      });
                    },
                  );
                },
                options: CarouselOptions(
                  height: MediaQuery.of(context).size.height * 0.5,
                  viewportFraction: 0.8,
                  initialPage: 0,
                  enableInfiniteScroll: true,
                  reverse: false,
                  autoPlay: false,
                  enlargeCenterPage: true,
                  onPageChanged: (index, reason) {
                    print('Page changed to index: $index');
                    setState(() {
                      _logic.setCurrentIndex(index);
                      _logic.hideDetails();
                    });
                    _logic.stopAudio();
                    _logic.playNextCard();
                  },
                ),
                carouselController: _carouselController,
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.fromLTRB(16.0, 0, 16.0, 160.0),
            child: ElevatedButton(
              onPressed: _logic.togglePlayPause,
              child: _logic.isPlaying
                  ? const Icon(Icons.pause) // 显示暂停图标
                  : const Icon(Icons.play_arrow), // 显示播放图标
            ),
          ),
        ],
      ),
    );
  }
}

class WordCarouselLogic {
  final AudioPlayer _audioPlayer = AudioPlayer();
  int _currentIndex = 0;
  bool _isPlaying = false;
  bool _showDetails = false;
  Timer? _timer;
  late List<WordCard> _sampleWords;
  late CarouselSliderController _carouselController;
  late _WordCarouselPageState _pageState;

  void init(_WordCarouselPageState pageState, List<WordCard> sampleWords,
      CarouselSliderController carouselController) {
    _pageState = pageState;
    _sampleWords = sampleWords;
    _carouselController = carouselController;
    playNextCard();
  }

  void dispose() {
    _audioPlayer.dispose();
    _timer?.cancel();
  }

  void playNextCard() {
    _audioPlayer.play(AssetSource('data/audio/whats-this.mp3'));
    if (!_isPlaying) return;

    print('Playing card at index: $_currentIndex');
    _showDetails = false;
    _pageState.setState(() {});

    _timer?.cancel(); // Cancel any existing timer
    _timer = Timer(Duration(seconds: 5), () {
      print('Showing details for card at index: $_currentIndex');
      
      _audioPlayer.play(UrlSource(
          'https://ali.bczcdn.com/r/${_sampleWords[_currentIndex].wordAudio}'));
      
      _showDetails = true;
      _pageState.setState(() {});

      _timer?.cancel(); // Cancel any existing timer
      _timer = Timer(Duration(seconds: 3), () {
        _currentIndex = (_currentIndex + 1) % _sampleWords.length;
        print('Moving to next card at index: $_currentIndex');
        _carouselController.jumpToPage(_currentIndex);
        playNextCard();
      });
    });
  }

  void togglePlayPause() {
    _isPlaying = !_isPlaying;
    _pageState.setState(() {});
    if (_isPlaying) {
      playNextCard();
    } else {
      _timer?.cancel();
      _audioPlayer.stop();
    }
  }

  void setCurrentIndex(int index) {
    _currentIndex = index;
  }

  void toggleShowDetails() {
    _showDetails = !_showDetails;
    if (_showDetails) {
      _pageState.setState(() {});

      _audioPlayer.play(UrlSource(
          'https://ali.bczcdn.com/r/${_sampleWords[_currentIndex].wordAudio}'));

      if (_isPlaying) {
        _timer?.cancel(); // Cancel any existing timer
        _timer = Timer(Duration(seconds: 3), () {
          _currentIndex = (_currentIndex + 1) % _sampleWords.length;
          print('Moving to next card at index: $_currentIndex');
          _carouselController.jumpToPage(_currentIndex);
          playNextCard();
        });
      }
    }
  }

  void hideDetails() {
    _showDetails = false;
  }

  void playAudio(String audioUrl) {
    _audioPlayer.play(UrlSource(audioUrl));
  }

  void stopAudio() {
    _audioPlayer.stop();
  }

  bool get isPlaying => _isPlaying;
  bool get showDetails => _showDetails;
  int get currentIndex => _currentIndex;
} 